package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.LoginDto;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Random;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private HttpServletRequest request;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody LoginDto loginDto) {
        Random random = new Random();
        int i = random.nextInt(1000000);
        System.out.println("验证码为:" + i);
        HttpSession session = request.getSession();
        session.setAttribute(loginDto.getPhone(), i);
        return R.success("发送成功");
    }

    @PostMapping("/login")
    public R login(@RequestBody LoginDto loginDto) {
        if (loginDto == null) {
            return R.error("参数错误");
        }
        HttpSession session = request.getSession();
        Integer code = (Integer) session.getAttribute(loginDto.getPhone());
        if (code == null) {
            return R.error("请先获得验证码");
        }
        if (!code.equals(loginDto.getCode())) {
            return R.error("验证码错误");
        }
        User user = userService.login(loginDto.getPhone());
        if (user == null) {
            User user1 = userService.add(loginDto.getPhone());
            session.setAttribute("userId", user1.getId());
            return R.success("成功");
        }
        session.setAttribute("userId", user.getId());
        return R.success("成功");
    }
    @PostMapping("/loginout")
    public R loginout(){
        HttpSession session = request.getSession();
        session.invalidate();
        return R.success("退出");
    }
}
